package com.my.netty.basic.eventloop;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        //拿到channel对象
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Channel channel = new Bootstrap()
            .group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel sc) throws Exception {
                    sc.pipeline().addLast(new StringEncoder());
                }
            })
            .connect(new InetSocketAddress("localhost", 8080))
            .sync()
            .channel();
        log.info("已连接连接服务端 {}", channel);
        Scanner sc = new Scanner(System.in);
        String line;
        do {
            System.out.println("输入向服务端发送的数据：");
            line = sc.nextLine();
            channel.writeAndFlush(line);
        } while (!"q".equalsIgnoreCase(line));
        sc.close();
        //用close还没法关闭所有线程
        channel.close();
        //停止线程需要调用EventLoopGroup的shutdown
        eventLoopGroup.shutdownGracefully();
        log.info("客户端退出");
    }
}
